<template>
  <forms ref="forms" :config="config" @submit:forms="onsubmit" :btns="btns">
    <template v-slot:price_extend="{row}">
      <input type="hidden" :name="row.name" :value="price_extend_encode(row.value)">
      <p v-for="(v,i) in row.value" style="line-height: 1.6;padding: 02px;">
        <span>{{v.num}}个月：￥{{v.price}}</span>
        <el-button size="small" type="danger" @click="row.value.splice(i,1)">删除</el-button>
      </p>
      <json_param :config="json_param_config" v-model:value="price_extend_row"></json_param>
      <el-button @click="add_price_extend" size="small">添加</el-button>
    </template>
    <template v-slot:hr="{row}">
      ---------------------------{{row.value}}---------------------------
    </template>
  </forms>
</template>

<script>
import {ajax} from "@/js/api_tool.js";
import {iframe} from "@/js/tool.js";
import s94Mjs from "s94-js";

export default {
  props: ['__iframe'],
  data(){
    let id = this.$get('id'), btns = undefined;
    let forms_config = {
      name: {label:'租户名',name:'name',type:id?'':'text_one',tips:'租户名，同时作为域名前缀，只能小写字母数字和下划线，唯一，不可更改'},
      encode_id: {label:'加密ID',name:'encode_id',tips:'加密后的租户ID，用于前端接口（对外开放没有权限验证）在获取租户详情时使用'},
      title: {label:'标题',name:'title',type:'text_one',tips:''},
      head_img: {label:'头图',name:'head_img',type:'file_img',tips:'头图，便于识别'},
      host: {label:'自定义域名',name:'host',type:'text_one',tips:'设定除默认的系统域名外的自定义域名'},
      link_truename: {label:'负责人姓名',name:'link_truename',type:'text_one',tips:'请输入负责人姓名'},
      phone: {label:'负责人电话',name:'phone',type:'text_one',tips:'请输入负责人电话'},
      link_info: {label:'负责人职位',name:'link_info',type:'text_one',tips:'请输入负责人职位'},
      expiration_time: {label:'到期时间',name:'expiration_time',type:'date',tips:'为空表示永久'},
      allow_expiration:{label:'允许过期', name:'allow_expiration', type: 'duration', tips:'租户到期后，在允许到期的时限内，暂时不会中断服务', value:0},
      template: {label:'模板',name:'template',type:'select_one',config:[],tips:'前端启用的模板',value:''},
      tenant_package_id: {label:'租户套餐',name:'tenant_package_id',type:'select_one',config:[],tips:'',value:''},
      price_extend: {label:'价格扩展',name:'price_extend',type:'price_extend',tips:'',value:[]},
      kickback_type_ids: {label:'分佣类型',name:'kickback_type_ids',type:'list_ids',config:'kickback_type/index',tips:'',value:''},
      authorisation: {label:'授权信息',name:'authorisation',type:'text_more',tips:'线上在页面底部的授权信息。如果包含图片可以传入html代码'},
    }
    if (id){
      forms_config.create_time = {label:'创建时间',name:'create_time',tips:''};
    }else {
      Object.assign(forms_config, {
        hr: {label:'分割线',type:'hr',tips:'',value:'以下为租户超级管理员设定'},
        admin_name: {label:'用户名',name:'admin_name',type:'text_one',tips:'用户名，登录用，不可修改',value:'admin'},
        password: {label:'密码',name:'password',type:'text_one',tips:''},
        nickname: {label:'昵称',name:'nickname',type:'text_one',tips:'',value:'超级管理员'},
        truename: {label:'真实姓名',name:'truename',type:'text_one',tips:'',value:'超级管理员'},
      })
    }
    if (this.$get('is_info')){
      s94Mjs.each(forms_config, function (row){ row.is_info = true; });
      btns = [];
    }
    return {
      id: id,
      btns: btns,
      config: forms_config,
      json_param_config: {
        num: {label:'时长(月)',name:'num',type:'text_one',config:'number',tips:''},
        price: {label:'价格',name:'price',type:'text_one',config:'number',tips:''},
      },
      price_extend_row: '{}',
    }
  },
  methods: {
    onsubmit(formData){
      let url = this.id ? `/admin/tenant/edit?id=`+this.id : '/admin/tenant/add';
      ajax({url:url, method:'POST', data:formData}, (res)=>{
        if (this.__iframe){
          iframe.exe('tenant/index', '$refs.list_url.list');
          iframe.hide('tenant/edit');
          if (!this.id) this.$refs['forms'].init();
        }else {
          this.$router.push('index');
        }
      }, (res)=>{
        if (res.errors) this.$refs['forms'].errors = res.errors;
      })
    },

    price_extend_encode(arr){
      let obj = {};
      let unit = 3600*24*30;
      s94Mjs.each(arr, function (v){
        obj[unit*v.num] = v.price;
      })
      return JSON.stringify(obj);
    },
    price_extend_decode(str){
      let one_moon = 3600*24*30;
      let res = [];
      s94Mjs.each(str ? JSON.parse(str) : [], function (v,k){
        res.push({num: Math.round(k/one_moon), price: v})
      })
      return res;
    },
    add_price_extend(callback){
      let app = this;
      callback = typeof(callback) =='function' ? callback : function (){app.$message.error('添加完成');}
      let row = JSON.parse(app.price_extend_row);
      let old_data = app.config.price_extend.value;
      if (row.price <= 0) return app.$message.error('设定的价格必须大于0！');
      if (row.num <= 0 || row.num != Math.round(row.num)) return app.$message.error('设定的时长(月)必须大于0，并且为整数');
      for (let i = 0; i < old_data.length; i++) {
        if (old_data[i].num == row.num) return app.$message.error('设定的时长(月)不能重复');
      }
      app.config.price_extend.value.push(row);
      app.price_extend_row = '{}';
    },
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;
    if (this.id) {
      ajax({url:'/admin/tenant/info?id='+this.id, cache:true}, (res)=>{
        res.data.price_extend = app.price_extend_decode(res.data.price_extend);
        this.$refs['forms'].init(res.data);
        return false;
      }, ()=>{
        if (this.__iframe){
          iframe.remove('tenant/edit');
        }else {
          this.$router.push('index');
        }
      })
    }

    //其他初始化操作
    ajax({url:'/admin/tenant_package/list',cache:true},function(res){
      app.config.tenant_package_id.config = app.decode_config(res.data.list, {content_key:'title',value_key:'id'})
      return false
    })
    ajax({url:'/admin/tenant/config_map',cache:true},function(res){
      app.config.template.config = res.data.template;
      return false
    })
  }
}
</script>
